<template>
  <div>
    <my-breadcrumb :items="['社区管理', '帖子管理']"/>
    <search :formItems="searchItems" :check="true" @search="getList" ref="search"/>
    <div class="add">
      <el-button type="primary" @click="toAdd">新增帖子</el-button>
      <el-button type="primary" @click="toExport" :loading="loading">导出帖子</el-button>
    </div>
    <el-table :data="posts" border @sort-change="orderByTime">
      <el-table-column
        type="index"
        width="55">
      </el-table-column>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="ID"
        prop="id">
      </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        sortable="custom"
        width="100px"
        prop="createtime">
        <template slot-scope="scope">
          <p>{{ scope.row.createtime.split(' ')[0] }}</p>
          <p>{{ scope.row.createtime.split(' ')[1] }}</p>
        </template>
      </el-table-column>
      <el-table-column
        label="帖子标题"
        width="200px"
        prop="title">
      </el-table-column>
      <!--<el-table-column
        label="发布时间"
        align="center"
        prop="updatetime">
      </el-table-column>-->
      <el-table-column
        label="发帖人"
        prop="membername">
      </el-table-column>
      <el-table-column
        label="分类标签"
        prop="labelid">
        <template slot-scope="scope">
          {{ labels[scope.row.labelid - 1] ? labels[scope.row.labelid - 1].name : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="所属话题"
        prop="topic">
      </el-table-column>
      <el-table-column
        label="评论量"
        sortable="custom"
        width="90px"
        prop="commentcount">
      </el-table-column>
      <el-table-column
        label="点赞量"
        sortable="custom"
        width="90px"
        prop="fabulous">
      </el-table-column>
      <el-table-column
        label="阅读量"
        sortable="custom"
        width="90px"
        prop="clickcount">
      </el-table-column>
      <el-table-column
        label="收藏量"
        sortable="custom"
        width="90px"
        prop="collcount">
      </el-table-column>
      <el-table-column
        label="是否置顶"
        sortable="custom"
        width="110px"
        prop="istop">
        <template slot-scope="scope">
          {{ scope.row.istop === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否官方"
        prop="isadmin">
        <template slot-scope="scope">
          {{ scope.row.isadmin === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        label="删除原因"
        prop="delcontent">
      </el-table-column>
      <el-table-column
        label="操作"
        width="180px"
        fixed="right"
        prop="id">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toUpdate(scope.row)" :disabled="scope.row.delflag === '1'">编辑</el-button>
          <el-button v-if="scope.row.delflag === '0'" size="mini" type="text" @click="toDelete(scope.row.id, scope.row.memberid, scope.row.title)">删除</el-button>
          <el-button v-else size="mini" type="text" disabled>已删除</el-button>
          <el-button size="mini" type="text" @click="toGetComment(scope.row.id)" :disabled="scope.row.delflag === '1'">查看评论</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <el-dialog :title="isAdd ? '新增帖子' : '信息修改'" :visible.sync="showAdd">
      <el-form :model="post" :rules="rules" inline label-width="90px" ref="addForm">
        <el-form-item label="ID" prop="id">
          <el-input v-model="post.id" disabled style="width: 220px;"/>
        </el-form-item>
        <el-form-item label="帖子标题" prop="title">
          <el-input v-model="post.title" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="发帖时间" prop="createtime">
          <el-date-picker
            v-model="post.createtime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发帖内容" prop="content">
          <el-input v-model="post.content" type="textarea" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="分类标签" prop="labelid">
          <el-select v-model="post.labelid">
            <el-option v-for="(item, index) in labels" :key="index" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属话题" prop="topicid">
          <div class="select-box" style="width: 500px;">
            <span v-if="nowTopic.title">{{ nowTopic.title }}</span>
            <el-button type="text" @click="toSelectTopic">点击选择话题</el-button>
          </div>
          <!--<el-select v-model="post.topicid">-->
            <!--<el-option v-for="(item, index) in topics" :key="index" :value="item.id" :label="item.title"/>-->
          <!--</el-select>-->
        </el-form-item>
        <el-form-item label="评论量" prop="commentcount">
          <el-input v-model="post.commentcount"/>
        </el-form-item>
        <el-form-item label="点赞量" prop="fabulous">
          <el-input v-model="post.fabulous"/>
        </el-form-item>
        <el-form-item label="收藏量" prop="collcount">
          <el-input v-model="post.collcount"/>
        </el-form-item>
        <el-form-item label="阅读量" prop="clickcount">
          <el-input v-model="post.clickcount"/>
        </el-form-item>
        <el-form-item label="推荐值" prop="orderby">
          <el-input v-model="post.recommend"/>
        </el-form-item>
        <el-form-item label="是否置顶" prop="istop">
          <el-select v-model="post.istop">
            <el-option value="0" label="否"/>
            <el-option value="1" label="是"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否官方" prop="isadmin">
          <el-select v-model="post.isadmin">
            <el-option value="0" label="否"/>
            <el-option value="1" label="是"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="imgarr">
          <div class="img-box" v-for="(image, index) in imageArr" :key="index">
            <img :src="image" class="avatar">
            <i class="el-icon-close" @click="delImage(index)"></i>
          </div>
          <el-upload
            class="avatar-uploader"
            action="#"
            v-if="imageArr.length < 6"
            :show-file-list="false"
            :before-upload="beforeUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="primary" @click="toSubmit">提交</el-button>
        <el-button type="danger" @click="showAdd = false">取消</el-button>
      </div>
    </el-dialog>
    <comment ref="comment"/>
    <select-list ref="selectList" :url="'/Topic/index?delflag=0'" :searchItems="topicSearch" :tableItem="topicTableItems" @selectRow="topicChange"/>
  </div>
</template>

<script>
import CLAZZ from '@/config/classify'
import {toExport, getPosts, deletePrompt} from '../../utils/getList'
import comment from '@/components/common/comment'
import selectList from '@/components/common/selectList'
import tableItems from '@/config/tableItems'
export default {
  name: 'post',
  data () {
    return {
      searchItems: [
        {
          label: '帖子标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '发帖人',
          type: 'input',
          key: 'membername'
        },
        {
          label: '帖子分类',
          type: 'select',
          key: 'labelid',
          options: CLAZZ.labelid
        },
        {
          label: '是否官方',
          type: 'select',
          key: 'isadmin',
          options: [{name: '否', id: '0'}, {name: '是', id: '1'}]
        },
        {
          label: '所属话题',
          type: 'select-filterable',
          key: 'topicid',
          options: []
        },
        {
          label: '发布时间',
          type: 'times',
          key: 'time'
        },
        {
          label: '是否置顶',
          type: 'select',
          key: 'istop',
          options: [{name: '否', id: '0'}, {name: '是', id: '1'}]
        }
      ], // 检索结构
      topicSearch: [
        {
          label: '话题标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '话题时间',
          type: 'times',
          key: 'times'
        }
      ],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      posts: [],
      isAdd: true,
      showAdd: false,
      post: {
        id: '',
        title: '',
        createtime: '',
        content: '',
        labelid: '',
        topicid: '',
        fabulous: '',
        commentcount: '',
        collcount: '',
        clickcount: '',
        recommend: '',
        istop: '',
        isadmin: '',
        imgarr: []
      },
      imageArr: [],
      rules: {
        memberId: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入帖子标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入帖子内容', trigger: 'blur' }
        ],
        labelid: [
          { required: true, message: '请选择分类标签', trigger: 'blur' }
        ]
      },
      labels: CLAZZ.labelid,
      loading: false,
      lifting: null,
      topics: [],
      nowTopic: {},
      topicTableItems: tableItems.topicList
    }
  },
  methods: {
    getList () {
      let searchData = {delflag: '0'}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      let params = {...searchData, page: this.page.pageNum, size: this.page.pageSize, orderby: this.lifting}
      this.axios.get('/article/index', {params})
        .then(res => {
          if (res.data.status) {
            this.page.total = Number(res.data.data.count)
            let tempArr = []
            this.topics.forEach(item => {
              tempArr[item.id] = item
            })
            res.data.data.list.forEach(item => {
              item.topic = tempArr[item.topicid] ? tempArr[item.topicid].title : '暂无信息'
            })
            this.posts = res.data.data.list
          }
        })
    },
    handleSizeChange (e) {
      this.page.pageSize = e
      this.getList()
    },
    handleCurrentChange (e) {
      this.page.pageNum = e
      this.getList()
    },
    toAdd () {
      this.isAdd = true
      this.showAdd = true
      this.imageArr = []
      this.nowTopic = {}
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
        this.$refs['addForm'].clearValidate()
      })
    },
    toUpdate (row) {
      this.isAdd = false
      this.showAdd = true
      this.nowTopic = {name: row.topic}
      this.$nextTick(() => {
        Object.keys(this.post).forEach(key => {
          this.post[key] = row[key]
        })
        this.imageArr = []
        this.post.imgarr = []
        Object.keys(row).forEach(key => {
          if (key.indexOf('img') === 0 && row[key]) {
            this.imageArr.push(row[key])
            this.post.imgarr.push(row[key])
          }
        })
        this.$refs['addForm'].clearValidate()
      })
    },
    toSubmit () {
      let url = '/article/add'
      if (!this.isAdd) {
        url = '/article/edit'
      }
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.axios.post(url, this.qs.stringify(this.post))
            .then(res => {
              if (res.data.status === 1) {
                this.getList()
                this.showAdd = false
                this.$message.success(res.data.msg)
              }
            })
        } else {
          this.$message.error('请检查表单是否填写正确')
          return false
        }
      })
    },

    toDelete (id, memberId, title) {
      deletePrompt({url: '/article/delete', id, memberId, title}, res => {
        if (res.data.status === 1) {
          this.getList()
          this.$message.success('删除成功')
        }
      })
    },

    toExport () {
      this.loading = true
      let searchData = this.$refs['search'].search()
      toExport('/Article/excelindex', searchData, '帖子', () => {
        this.loading = false
      })
    },

    orderByTime (lifting) {
      if (lifting.order === 'ascending') {
        this.lifting = lifting.prop + ' asc'
      } else {
        this.lifting = lifting.prop + ' desc'
      }
      this.getList()
    },

    toGetComment (id) {
      this.$refs['comment'].getList({type: '2', parid: id})
    },

    beforeUpload (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.imageArr.push(ev.currentTarget.result)
        _self.post.imgarr.push(ev.currentTarget.result)
      }
      reader.readAsDataURL(file)
      return false
    },
    delImage (index) {
      this.imageArr.splice(index, 1)
      this.post.imgarr.splice(index, 1)
    },

    toSelectTopic () {
      this.$refs['selectList'].toShow()
    },
    topicChange (row) {
      console.log(row)
      this.nowTopic = row
      this.post.topicid = row.id
    }
  },
  mounted () {
    this.showAdd = false
  },
  components: {
    comment,
    selectList
  },
  created () {
    getPosts(data => {
      this.topics = data
      let tempArr = []
      data.forEach(item => {
        tempArr.push({
          id: item.id,
          name: item.title
        })
      })
      this.searchItems[4].options = tempArr
      this.getList()
    })
  }
}
</script>

<style scoped>
  .avatar-uploader{
    display: inline-block;
    overflow: hidden;
  }
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .img-box{
    display: inline-block;
    position: relative;
  }
  .img-box i{
    position: absolute;
    top: 10px;
    right: 10px;
  }
  .avatar {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    border-radius: 6px;
    overflow: hidden;
  }
</style>
